// 会议结论填写
<template>
  <layoutDividerPage class="conclusion">
    <template #search>
      <div class="button-list">
        <el-button type="primary" @click="submitForm">退出编辑</el-button>
      </div>
    </template>

    <div class="tab-box">
      <vxe-grid
        ref="xGrid"
        border
        stripe
        keep-source
        auto-resize
        sync-resize
        :loading="listLoading"
        :column-config="{ resizable: true }"
        :export-config="{}"
        :columns="tableColumn"
        align="left"
        :row-config="{ keyField: 'id', isCurrent: true, isHover: true }"
      >
        <template #form>
          <div class="button-add">
            <el-button type="primary" plain @click="handleAdd">
              <el-icon class="el-icon--left"><CirclePlus /></el-icon>
              增加内容
            </el-button>
          </div>
        </template>
        <template #relatedDocuments="{ row }">
          <div v-for="item in row.relatedDocuments" :key="item.id">
            <el-link
              v-if="item.fileUrl"
              :underline="false"
              type="primary"
              @click="handleClickDoc(item)"
            >
              文档：{{ item.fileName }}
            </el-link>
            <span v-else>文档：{{ item.fileName }}</span>
          </div>
        </template>
        <template #associationInfos="{ row }">
          <div v-for="item in row.associationInfos" :key="item.id">
            <el-link
              v-if="routeTypes[item.associationType]"
              :underline="false"
              type="primary"
              @click="handleClickAssociation(item)"
            >
              项目名称：{{ item.associationContent }}（项目编号：{{
                item.associationId
              }}）
            </el-link>
            <span v-else>
              项目名称：{{ item.associationContent }}（项目编号：{{
                item.associationId
              }}）
            </span>
          </div>
        </template>
        <template #options="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </vxe-grid>
    </div>
  </layoutDividerPage>
  <el-dialog
    v-model="conclusionVisible"
    :title="conclusionTitle"
    destroy-on-close
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleFormClose"
  >
    <el-form
      ref="conclusionFormRef"
      :model="conclusionForm"
      :rules="conclusionRules"
      status-icon
      label-position="top"
    >
      <el-form-item label="结论内容" prop="conclusionContent">
        <el-input
          v-model="conclusionForm.conclusionContent"
          type="textarea"
          :rows="5"
          placeholder="请输入"
          clearable
        />
      </el-form-item>
      <el-form-item label="上传文档" prop="fileList">
        <el-upload
          v-model:file-list="conclusionForm.fileList"
          :http-request="customUpload"
          :before-upload="beforeUpload"
          :on-remove="handleRemove"
          multiple
        >
          <el-button type="primary" plain>
            <el-icon class="el-icon--left"><Upload /></el-icon>
            上传
          </el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="关联信息：" required>
        <el-table :data="conclusionForm.items" border>
          <el-table-column label="序号" type="index" width="80" />
          <el-table-column label="内容">
            <template #default="scope">
              <el-form-item
                :prop="`items.${scope.$index}.associationId`"
                :rules="conclusionRules.items[0].fields.associationId"
              >
                <el-select-v2
                  v-model="scope.row.associationId"
                  filterable
                  :options="associationContent"
                  placeholder="请选择"
                  clearable
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160">
            <template #default="scope">
              <el-button type="danger" link @click="removeItem(scope.$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="addItem">
          <el-icon class="el-icon--left"><CirclePlus /></el-icon>
          增加关联信息
        </el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="conclusionVisible = false">取消</el-button>
      <el-button type="primary" @click="handleFormSumbit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
  import type { FormInstance, FormRules, FormItemRule } from 'element-plus'
  import layoutDividerPage from '@/components/layoutDividerPage.vue'
  import {
    conclusionDialogProps,
    optionsProps,
    resProps,
    resDetailsProps,
    MeetingConclusionsRespVO,
    RelatedDocumentsRespVO,
    MeetingAssociationsRespVO,
  } from '../../interface'
  import {
    getMeetingsWriteConclusions,
    getMeetingsDetails,
    deleteMeetingsConclusions,
  } from '@/api/project/meeting'
  import { postActionUpload } from '@/api/requestEvents'
  import { useCloseTabNavigate } from '@/utils/useCloseTabNavigate'

  const { closeTabNavigate } = useCloseTabNavigate()

  // 路由实例
  const router = useRouter()
  const route = useRoute()

  // 配置一个路由名称与类型映射关系
  const routeTypes = {
    TOPIC_ADVICE: 'Meeting',
  }
  const tableColumn = [
    { title: '序号', type: 'seq', minWidth: 50 },
    { title: '内容', field: 'conclusionContent', minWidth: 50 },
    {
      title: '文档',
      field: 'relatedDocuments',
      minWidth: 120,
      slots: { default: 'relatedDocuments' },
    },
    {
      title: '关联信息',
      field: 'associationInfos',
      minWidth: 120,
      slots: { default: 'associationInfos' },
    },
    {
      title: '操作',
      field: 'options',
      minWidth: 80,
      slots: { default: 'options' },
    },
  ]
  // 表格实例
  const xGrid = ref(null)
  // 加载状态
  const listLoading = ref<boolean>(false)

  // 关联信息变量
  const associationContent = ref<optionsProps[]>([])
  // 对话框 标题名
  const conclusionTitle = ref<string>('')
  // 对话框 是否显示
  const conclusionVisible = ref<boolean>(false)
  // form 表单 实列
  const conclusionFormRef = ref<FormInstance>()
  // form 表单变量
  const conclusionForm = reactive<Partial<conclusionDialogProps>>({
    items: [],
    relatedDocumentList: [],
  })
  // form 表单 校验规则
  const conclusionRules = reactive<FormRules<conclusionDialogProps>>({
    conclusionContent: [
      {
        required: true,
        message: '请输入结论内容',
        trigger: 'blur',
      },
    ],
    fileList: [
      {
        required: true,
        message: '请上传文件',
        trigger: 'blur',
      },
    ],
    items: [
      {
        type: 'array',
        required: true,
        fields: {
          associationId: {
            type: 'number',
            required: true,
            message: '请选择内容',
            trigger: 'blur',
          } as FormItemRule,
        },
      },
    ],
  })

  // 添加关联信息
  const addItem = () => {
    conclusionForm.items.push({ associationId: '' })
  }

  // 移除关联信息
  const removeItem = (index: number) => {
    conclusionForm.items.splice(index, 1)
  }

  // 关闭 清空form 表单
  const handleFormClose = () => {
    conclusionFormRef.value.resetFields()
    editorId.value = ''
  }
  // 表单提交 校验
  const handleFormSumbit = async () => {
    const valid = await conclusionFormRef.value.validate()
    if (valid) {
      console.log('表单校验通过，提交数据:', conclusionForm)
      try {
        conclusionForm.relatedDocumentList = conclusionForm.fileList.map(
          (file) => ({
            fileName: file.name,
            fileType: file.type,
            fileUrl: file.url,
            fileId: file.id,
          })
        )
        const tempAssociation = conclusionForm.items?.map((item) => {
          return item.associationId
        })
        const params = {
          conclusionContent: conclusionForm.conclusionContent,
          relatedDocumentList: conclusionForm.relatedDocumentList,
          associationIds: tempAssociation.join(',') || '',
          meetingId: route.query?.id,
          id: editorId.value,
        }
        const res: resProps = await getMeetingsWriteConclusions(params)
        if (res && res.code === 0) {
          ElMessage.success('提交成功')
          // 应该再次查询会议详细信息
          handleSearchDetails()
          conclusionVisible.value = false
        } else {
          ElMessage.error(`提交失败: ${res.msg || '未知错误'}`)
        }
      } catch (e) {
        console.error('提交失败', e)
      }
    } else {
      console.error('表单校验未通过')
    }
  }
  // 文档下载
  const handleClickDoc = (item: RelatedDocumentsRespVO) => {
    console.log('handleClickDoc', item)
    window.open(item.fileUrl, '_blank')
  }

  // 定义一个编辑内容
  const editorId = ref<string | number>()
  // 关联信息跳转
  const handleClickAssociation = (item: MeetingAssociationsRespVO) => {
    router.push({
      name: routeTypes[item.associationType],
      query: { id: item.associationId },
    })
  }
  // 编辑内容
  const handleEdit = (row: MeetingConclusionsRespVO) => {
    conclusionTitle.value = '编辑内容'
    conclusionVisible.value = true

    console.log('wewweewwe', row)
    const tempFileList = row.relatedDocuments?.map((item) => {
      return {
        name: item.fileName,
        url: item.fileUrl,
        type: item.fileType,
        id: item.fileId,
      }
    })
    const tempItem = row.associationInfos?.map((item) => {
      return {
        associationId: item.id,
      }
    })
    Object.assign(conclusionForm, {
      conclusionContent: row.conclusionContent,
      fileList: tempFileList || [],
      items: tempItem || [],
    })
    editorId.value = row.id
  }
  // 增加内容
  const handleAdd = () => {
    conclusionTitle.value = '增加内容'
    conclusionVisible.value = true
  }

  // 删除列表项
  const handleDelete = (row: MeetingConclusionsRespVO) => {
    ElMessageBox.confirm(`确定删除结论?`, '删除结论', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const params = {
        conclusionId: row.id,
      }
      const res: resProps = await deleteMeetingsConclusions(params)
      console.log('res', res.code === 0)
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      }
      handleSearchDetails()
    })
  }
  // // 确认提交
  const submitForm = () => {
    closeTabNavigate({
      name: 'Meetings_Details',
      query: { id: route.query?.id },
    })
  }

  // 文件上传前的检查
  const beforeUpload = (file: File) => {
    const isLt5M = file.size / 1024 / 1024 < 5
    if (!isLt5M) {
      ElMessage.error('上传文件大小不能超过 5MB!')
    }
    return isLt5M
  }

  const handleRemove = (file, uploadFiles) => {
    console.log(file, uploadFiles)
  }
  // 文件自定义上传
  const customUpload = async (options: any) => {
    const formData = new FormData()
    formData.append('file', options.file)
    try {
      // 调用 getFileUploadReturn 接口获取上传文件的返回信息
      const resUpload: any = await postActionUpload(
        '/infra/file/upload-return-obj',
        formData,
        options
      )
      if (resUpload.code === 0 && resUpload.data) {
        const fileItem = conclusionForm.fileList.find(
          (item) => item.uid === options.file.uid
        )
        if (fileItem) {
          fileItem.name = resUpload.data.name
          fileItem.url = resUpload.data.url
          fileItem.id = resUpload.data.id
          fileItem.type = resUpload.data.type
        }

        ElMessage.success('文件上传成功')
      } else {
        conclusionForm.fileList = conclusionForm.fileList.filter(
          (item) => item.uid !== options.file.uid
        )
      }
    } catch (error) {
      ElMessage.error('文件上传失败')
      console.error('文件上传失败', error)
      conclusionForm.fileList = conclusionForm.fileList.filter(
        (item) => item.uid !== options.file.uid
      )
    }
  }

  // 查询明细
  const handleSearchDetails = async () => {
    try {
      if (!route.query?.id) return
      const res: resDetailsProps = await getMeetingsDetails({
        id: route.query.id,
      })
      if (!res || !res.data) {
        console.error('未获取到会议明细数据')
        return
      }
      // 需要获取这个会议里面的关联信息
      const { associations, conclusions } = res.data
      associationContent.value = associations.map((item) => {
        return {
          label: item.associationContent,
          value: item.id,
        }
      })

      xGrid.value.reloadData(conclusions || [])
    } catch (e) {
      console.error('查询会议明细异常', e)
    }
  }

  watch(
    () => ({
      id: route.query?.id,
    }),
    ({ id }: { id: string }) => {
      if (id) {
        handleSearchDetails()
      }
    },
    { immediate: true }
  )
</script>

<style lang="scss" scoped>
  .conclusion {
    .button-list {
      display: flex;
      align-items: center;
      justify-content: end;
      margin: 20px;
    }

    .button-add {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
    }
    .tab-box {
      padding: 20px;
    }
  }
  :deep(.el-table) {
    .el-form-item {
      margin-bottom: 0;
    }
    .el-form-item__error {
      position: static;
      white-space: nowrap;
    }
  }
</style>
